
let timer; 
let onDrawing = false;  // 是否可进行抽奖标识，默认为false可进行抽奖
let drawIndex = 0; //抽奖过程KEY

// pages/my/my.js
import {
    getbaseUrl,
    requestUtil
} from "../../utils/request"

import {dateConversion} from "../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // prizeList: [
    //   { id: '001', index: 1, imgsrc: 'https://hbimg.huabanimg.com/18b925338313c77ee90c6a0a2f052a7988e10ce515ca7-T4bMZ0_fw658', prizeName: '谢谢参与' },
    //   { id: '002', index: 2, imgsrc: 'https://hbimg.huabanimg.com/2acfd641286f1a7e4050ca13e207c1d2fc2cbf5f12ca2-W5O1vm_fw658', prizeName: '金币 x20' },
    //   { id: '003', index: 3, imgsrc: 'https://hbimg.huabanimg.com/72138f8f82134a9099eaa02d5d81fa738519716021e4c-idXlQk_fw658', prizeName: '火箭 x1' },
    //   { id: '004', index: 4, imgsrc: 'https://hbimg.huabanimg.com/96e0a27d3a6b25dacd7157db6879b63be9e1addd126ac-sMVvOt_fw658', prizeName: '神秘礼盒 x1' },
    //   { id: '005', index: 5, imgsrc: 'https://hbimg.huabanimg.com/aa694a1e151f2cb8d8583eee9d1cbf0342b5577b953c-O0MFoR_fw658', prizeName: '水晶血瓶 x1' },
    //   { id: '006', index: 6, imgsrc: 'https://hbimg.huabanimg.com/2fe60709c9479b41ec3eef7fff1101f683b4ad89254af-HNdtDR_fw658', prizeName: '金币 x10' },
    //   { id: '007', index: 7, imgsrc: 'https://hbimg.huabanimg.com/407d1f6d9aa47e757994d9474dba7257c4c73bd11123a-5juBN1_fw658', prizeName: '水晶钻石 x5' },
    //   { id: '008', index: 8, imgsrc: 'https://hbimg.huabanimg.com/513f6f7d9f323e7cc3e252444237a84b52a98890c375-LGfXRi_fw658', prizeName: '水晶盒 x1' },
    // ],
    prizeList:[],
    drawIndex: null, //抽奖过程KEY,
    prizeResult:null, //抽奖的结果
    prizeName:null,//抽奖结果KEY对应的奖品名称,
    isShowLuck:false,// 是否显示奖品弹窗，默认false不显示
    showAgain:false,//是否抽奖后显示再抽一次按钮
    awardImge:'https://hbimg.huabanimg.com/18b925338313c77ee90c6a0a2f052a7988e10ce515ca7-T4bMZ0_fw658', // 弹窗展示的奖品照
    awardName:"谢谢参与",// 弹窗展示的奖品名字
    
    // 用户金额
    money:100,
    oneReduceMoney:10,
    // 用户信息
    userInfo:{},
    show:false,
    baseUrl:''

  },

//   在逛逛
noTocharge(){
    this.setData({
        show:false
    })
},
// 去充值
Tocharge(){
    this.setData({
        show:false
    })
    wx.navigateTo({
      url: '/pages/recharge/recharge',
    })
},

  // 狗扣钱
  deduction(openId, money) {
    // let disRmb = this.data.disRmb
    requestUtil({
      url: "/shop/noMatchPassword",
      method: "get",
      data: {
        openId,
        money: -money
      }
    })
  },

  // 点击抽奖
  startDraw(){
      let openId = this.data.userInfo.openid
    // 是否可以抽奖
    if(onDrawing){
      return
    }else{
      onDrawing = true
    }
    let money = this.data.money
    let oneReduceMoney = this.data.oneReduceMoney
    if(money<oneReduceMoney){
        // console.log(money)
        this.setData({
            show:true
        })
      onDrawing=false
      return
    }
    let Reducemoney=(money-oneReduceMoney).toFixed(2)
    this.setData({
        money:Reducemoney
    })
    this.deduction(openId,oneReduceMoney)
    clearInterval(timer);
    timer = setInterval(()=>{
      this.changePrize()
    },80)

    let random =Math.floor(Math.random()*this.data.prizeList.length)
    
    let res = {
      status:1,
      prizeResult:this.data.prizeList[random].index,
      prizeName:this.data.prizeList[random].prizeName
    }

    if(res.status==1){
      setTimeout(()=>{
          clearInterval(timer)
          timer = setInterval(() => {
              this.changePrize()
          }, 200);

          setTimeout(()=>{
            clearInterval(timer)
            timer = setInterval(() => {
                this.changePrize()
            }, 420);

            setTimeout(()=>{
              this.setData({
                prizeResult:res.prizeResult,
                prizeName:res.prizeName
              })
            },1200)

          },1600)
          
      },2000)
    }


  },


  // 抽奖过程奖品切换
  changePrize(){
      drawIndex++;
      drawIndex = drawIndex>8?1:drawIndex;

      this.setData({
        drawIndex
      })

      if(this.data.prizeResult == drawIndex){
        clearInterval(timer)
        let currentAward = this.data.prizeList[this.data.prizeResult-1]
        this.addPrizes(currentAward)
        this.setData({
          showAgain:true,
          isShowLuck:true,
          awardImge:currentAward.imgsrc,
          awardName:currentAward.prizeName
        })
        this.getUserMoney()
      }

  },

//   把奖品添加到用户里面
addPrizes(data){
    if(data.class==0){
        // console.log("谢谢参与")
        return
    }
    let awardDate = dateConversion(new Date())
    let openId = this.data.userInfo.openid
    let Award = {
        ...data,
        openId,
        awardDate
    }
   let res = requestUtil({
       url:"/shop/addUserAward",
       method:"get",
       data:Award
   })
   res.then(r=>{
       if(r.data.status==200){
        // console.log("添加成功")
       }else{
        // console.log("添加失败")
       }
   })
},


  // 再一次抽奖
  againBtn(){
    onDrawing = false;
    drawIndex = 0;//抽奖过程

    this.setData({
      drawIndex:null,//清空抽奖过程
      prizeResult:null,//清空抽奖结果
      prizeName:null,//清空抽奖结果对应的奖品名
      showAgain:false,//是否抽奖后显示再抽一次按钮
      awardImge:"",//清空奖品展示的图片
      awardName:'',//清空奖品的展示名称
    })
  },

  // 跳到我的奖品页
  toMyAward(){
    wx.navigateTo({
      url: '/pages/awardPool/awardPool',
    })
  },

// 关闭弹窗
closePopup(){
  this.againBtn()
    this.setData({
      isShowLuck:false
    })
},

// 登录抽奖
login(){
    wx.getUserProfile({
        desc: "我点",
        lang: "zh_CN",
        success: (res) => {
            //   console.log(res.userInfo)
            let {
                avatarUrl,
                nickName,
                gender
            } = res.userInfo
            wx.login({
                success: (res) => {

                    let p = requestUtil({
                        url: "/my/emitUserPid",
                        method: "get",
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        data: {
                            code: res.code,
                            avatarUrl,
                            nickName,
                            gender
                        },

                    })
                    p.then(({
                        data
                    }) => {
                        //    console.log(data.data)
                        wx.setStorage({
                            key: "userInfo",
                            data: JSON.stringify(data.data),
                            success: () => {
                                this.getUserInfo()
                            }
                        })
                    })
                },
                fail: (err) => {
                    console.log(err)
                }
            })
        }


    })
},

// 获取用户的金额
getUserMoney(){
    let openId = this.data.userInfo.openid
    if(!openId)return
    let res = requestUtil({
        url:"/shop/getUserMoney",
        method:"get",
        data:{
            openId
        }
    })
    res.then(({data})=>{
        // console.log(data)
        let totalPrice = data.data.reduce((total,item)=>{
           return total += item.money
        },0)
        if(data.status==200){
            this.setData({
                money:totalPrice.toFixed(2)
            })
        }else{
            this.setData({
                money:0
            })
        }
    })
},

  // 获取本地的用户信息

  getUserInfo() {
    wx.getStorage({
        key: "userInfo",
        success: (res) => {
            // res.data
            this.setData({
                userInfo: JSON.parse(res.data)
            })
            this.getUserMoney()
        },
        fail: () => {
            this.setData({
                userInfo: {}
            })
        }

    })
},

// 获取奖池数据
getLuckDraw(){
    wx.showLoading({
      title: '数据加载中',
    })
    let res = requestUtil({
        url:"/shop/getLuckDraw",
        method:"get"
    })
    res.then(r=>{
        if(r.data.status==200){
            let drawData = r.data.data.map(item=>{
                return item
            })
           this.setData({
            prizeList:drawData
           })
           wx.hideLoading()
        }else{
            this.setData({
                prizeList:[]
               })
               wx.hideLoading()
        }
       
    })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      this.getLuckDraw()
      this.setData({
        baseUrl:getbaseUrl()+"/image/"
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserInfo()
    this.setData({
        onDrawing:false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})